<template>
  <div class="detail">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-position="right"
      label-width="130px"
    >
      <div class="form-data">
        <el-form-item label="模型中文名称" prop="cn_name">
          <el-input
            v-model="postForm.cn_name"
            placeholder="模型中文名称"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="模型表名称" prop="en_name">
          <el-input
            v-model="postForm.en_name"
            placeholder="模型表名称"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model.number="postForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <div class="model-fields-data-card">
          <el-button type="primary" style="margin-bottom: 10px" @click="addModelFieldsData">添加模型字段</el-button>
          <div
            v-for="(item, index) in postForm.fields_data"
            :key="'model_fields_data' + index"
          >
            <el-card style="margin-bottom: 10px">
              <div slot="header">
                <span>{{ postForm.cn_name }} 模型字段 {{ index }}</span>
                <el-button type="text" style="float: right;padding: 3px 0;color: red" @click="removeModelFieldsData(index)">删除</el-button>
              </div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="字段中文名">
                    <el-input
                      v-model="item.cn_name"
                      placeholder="字段中文名"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="字段英文名">
                    <el-input
                      v-model="item.en_name"
                      placeholder="字段英文名"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="配置项类型">
                <el-select
                  v-model.number="item.type"
                  placeholder="配置项类型"
                  style="width:100%"
                  @change="(val) => {changeItemType(val, index)}"
                >
                  <el-option v-for="(type_item, type_index) in item_type_name" :key="'operation_type' + type_index" :value="type_index + 1" :label="type_item" />
                </el-select>
              </el-form-item>
              <el-form-item
                v-show="(item.type === 2 || item.type === 3 || item.type === 4) ? true : false"
                label="可选值"
                prop="values"
              >
                <el-input
                  v-model="item.values"
                  type="textarea"
                  placeholder="可选值"
                  style="width: 100%"
                />
                <span class="form-item-tips">配置项的值，用英文,进行数据分割</span>
              </el-form-item>
              <el-form-item label="提示">
                <el-input
                  v-model="item.tips"
                  placeholder="提示"
                  style="width: 100%"
                />
              </el-form-item>
            </el-card>
          </div>
        </div>
      </div>

      <sticky :class-name="'sub-navbar'">
        <el-button
          v-loading="loading"
          type="success"
          style="margin-left: 10px"
          @click="submitForm"
        >
          {{ isEdit ? '编辑' : '添加' }}
        </el-button>
      </sticky>
    </el-form>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import { item_type_name } from '@/utils'
import { getModelTableByID, addModelTable, editModelTable } from '@/api/model-table'

const fields = {
  cn_name: '中文名称'
}

const validateRequire = (rule, value, callback) => {
  if (!value || value === '' || value.trim() === '') {
    const errMsg = fields[rule.field] + '为必填项'
    callback(new Error(errMsg))
  } else {
    callback()
  }
}

const validateEnName = (rule, value, callback) => {
  if (!(/^\w{1,80}$/.test(value))) {
    const errMsg = '字段名称只能包含英文字母、数字、_、-'
    // this.showMessage(errMsg, 'error')
    callback(new Error(errMsg))
  } else {
    callback()
  }
}

export default {
  name: 'ModelTableDetail',
  components: { Sticky },
  props: {
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      isEdit: false,
      loading: false,
      item_type_name,
      postForm: {
        cn_name: '',
        en_name: '',
        fields_data: [],
        sort: 1,
        status: 1
      },
      rules: {
        cn_name: [
          { required: true, message: '中文名称不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        en_name: [
          { required: true, message: '英文名称不能为空' },
          { validator: validateEnName, trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '排序不能为空' },
          { type: 'number', message: '排序值格式不正确' }
        ],
        status: [
          { required: true, message: '状态不能为空' },
          { type: 'number', message: '状态值格式不正确' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      if (!this.loading) {
        this.loading = true
        this.$refs.postForm.validate((valid, fields) => {
          // 判断规则是否通过验证
          if (valid) {
            const model_table = Object.assign({}, this.postForm)
            // console.log(menu)
            if (!this.isEdit) {
              addModelTable(model_table).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            } else {
              model_table.id = this.id
              editModelTable(model_table).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            }
          } else {
            this.loading = false
            for (const key in fields) {
              if (fields.hasOwnProperty(key)) {
                const element = fields[key]
                this.$message({
                  message: element[0].message,
                  type: 'error',
                  duration: 2000
                })
                return false
              }
            }
          }
        })
      }
    },
    getModelTableByID() {
      if (this.id !== 0) {
        getModelTableByID(this.id).then(response => {
          if (!response.data || response.data.length === 0) {
            this.isEdit = false
            return
          }
          const {
            cn_name,
            en_name,
            sort,
            status,
            fields_data
          } = response.data
          this.postForm = {
            cn_name,
            en_name,
            sort,
            status,
            fields_data
          }
          this.isEdit = true
        }).catch(() => {
          this.isEdit = false
          this.toDefault()
        })
      } else {
        this.isEdit = false
      }
    },
    toDefault() {
      this.$refs.postForm.resetFields()
      this.postForm.fields_data = []
      this.loading = false
    },
    addModelFieldsData() {
      this.postForm.fields_data.push({
        cn_name: '',
        en_name: '',
        values: '',
        type: '',
        tips: ''
      })
    },
    removeModelFieldsData(index) {
      this.postForm.fields_data.splice(index, 1)
    },
    changeItemType(value, index) {
      this.postForm.fields_data[index].values = ''
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
